$(function () {
    /** extendLocalStorage  在common.js 文件中抛出到全局window上
     * 
     */
    var videoArr = [];
    let userinfo = window.extendLocalStorage.get("userinfo");
    getCourse();
    $("#organCourse").click(async function (e) {
        e.preventDefault();
        $(this).addClass("active").siblings().removeClass("active");
        // getMyInterCourse(2);
        getCourse();
    });
    // 更换机构对应渲染列表内容
    $("#tabOrganization").on("click", "li", function (e) {
        e.preventDefault();
        getCourse();
    });
    /** 获取课程列表 */
    function getCourse() {
        let curOrgan = extendLocalStorage.get("curOrgan");
        if (!curOrgan) { //curOrgan为空时，默认属于
            $("#searchErr").show(200).find("#searchErrText").text("请先选择机构");
            return false;
        }
        $.ajax({
            url: `${testUrl}/platform/course/index?org_id=${curOrgan.org_id}&token=${userinfo.token}`,
            type: 'get',
            success: function (res) {
                if (!res.data.info.length) {
                    $("#searchErr").show(200);
                    return false
                }
                if (res.code == 1) {
                    $("#searchErr").hide(200);
                    $("#courseList").empty();
                    // console.log(res);
                    $.each(res.data.info, function (index, item) {
                        $("#courseList").append('<li _classHourId=' + item.id + '><a href="javascript:;"><img draggable="false" src="' + item.images[0] + '"><div><p>' + item.name + '</p><em class="iconfont iconshenglvehao"></em></div></a></li>');
                    });
                    clickCourseList();
                }
            }
        })
    }
    // 预览pptx  swiper初始化
    var swiper = new Swiper('.swiper-container-x', {
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        on: {
            slideChangeTransitionEnd: function () {
                $.each(videoArr, function (index, item) {
                    item.pause();
                })
            },
        },
        // effect: 'cube',
        mousewheel: true, //滚轮轮播
        // /过渡到slide一开始就加载，设置为true
        keyboard: true, //开启键盘控制翻页
        clickable: true,
        observer: true, //修改swiper自己或子元素时，自动初始化swiper
    });
    // 当点击一个课程列表时
    async function clickCourseList() {
        $("#courseList li").unbind("click").click(async function (e) {
            if ($(e.target)[0] == $(this).find("em")[0]) {
                return false;
            }
            let data = {
                token: userinfo.token,
                id: $(this).attr("_classHourId"),
                page:1,
                row:100
            };
            $("#courseList").empty(); //点击课程进入课时列表，先把课程展示删除
            let res = await sendAjax("get", '' + testUrl + '/platform/hour/index', data);
            if (res.code == 0 || res.data.info.length == 0) {
                getDefaultCourse();
                alert("此课程无数据");
                return false;
            }
            $.each(res.data.info, function (index, item) {
                $("#courseList").append(
                    '<li _classHourConId=' + item.id + ' ><a href="javascript:;"><img draggable="false" src="' + item.cover + '"><div><p>' + item.name + '</p><em class="iconfont iconshenglvehao"></em></div></a></li>'
                );
            });
            classListFn();
        });

    }
    // 用户进到首页先默认一个加载课时列表
    function classListFn() { //课时列表某一项，点出预览窗口出现
        $("#courseList>li").unbind("click").click(async function (e) {
            if ($(e.target)[0] == $(this).find("em")[0]) {
                return false;
            }
            //鼠标移出隐藏按钮，移入显示按钮
            $("#previewErr").hide();
            $("#loading").show();
            if (!userinfo) {
                $(".loginDialog").css("display", "block");
                return;
            }
            $(".previewPPTX").css("display", "block");
            // console.log($(this).attr("_classhourconid"));
            let data = {
                token: userinfo.token,
                id: $(this).attr("_classHourConId")
            };
            let res = await sendAjax("get", '' + testUrl + '/platform/hour/detail', data);
            if (!res.data) {
                $("#loading").hide();
                $("#previewErr").show();
                return false
            } else {
                if (res.data.plan.length !== 0) {
                    $("#previewErr").hide();
                } else {
                    $("#loading").hide();
                    $("#previewErr").show();
                }
            }
            $(".previewPPTX h3").text(res.data.name); //改变预览头部的标题
            let getArr = res.data.plan;
            is_screen = [];
            // console.log(getArr)
            $.each(getArr, function (index, item) {
                if (item.type == 1) { // 视频加图片
                    $(".swiper-wrapper").append(`<div class="swiper-slide" is_screen=${item.is_screen} is_type=${item.type}><img draggable="false" src="${item.cover}"><video controls src="${item.context}"></video></div>`);
                } else if (item.type == 3) { //音频加图片
                    $(".swiper-wrapper").append(
                        `<div class="swiper-slide" is_screen=${item.is_screen}><img draggable="false" src="${item.cover}"><audio controls src="${item.context}"></audio></div>`
                    );
                } else if (item.type == 4) { //多张图片
                    $.each(item.context, function (index, it) {
                        $(".swiper-wrapper").append(
                            `<div class="swiper-slide" is_screen=${item.is_screen}><img draggable="false" src="${it}"></div>`
                        );
                    });
                } else { //为图片
                    $(".swiper-wrapper").append(`<div class="swiper-slide" is_screen=${item.is_screen}><img draggable="false" src="${item.context}"></div>`)
                }
            });
            $("#loading").hide();
            // $(".swiper-wrapper").append(fragment);
            videoArr = $(".swiper-container video,.swiper-container audio");
            $(".swiper-slide[is_type]").unbind("click").click(function () {
                $(this).find("img").css("display", "none");
                $(this).find("video").css("display", "block");
            })
        });
    }

    // 监听火狐全屏事件和chrome
    function no_fullScreen() {
        $(".previewPPTX").css("display", "none");
        $(".screenFullNone").css("display", "block");
        $(".content").css("visibility", "visible");
        $(".loginDialog").css("display", "none");
        $(".connectErr").css("display", "none");
        $(".previewPPTX").css("display", "none");
        $(".previewPPTX .swiper-container").empty(); //点击课程进入课时列表，先把课程展示删除
        $(".previewPPTX .swiper-container").append('<div class="swiper-wrapper"></div><div class="swiper-button-next"></div><div class="swiper-button-prev"></div>');
        $(".centerBox").css({
            width: "61%",
        })
        $(".previewPPTX .PPTXCon").css("padding", "10px");
        var swiper = new Swiper('.swiper-container-x', {
            keyboard: true, //开启键盘控制翻页
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            on: {
                slideChangeTransitionEnd: function () {
                    // console.log(videoArr)

                    $.each(videoArr, function (index, item) {
                        item.pause();
                    })
                },
            },
            // effect: 'cube',
            mousewheel: true, //滚轮轮播
            clickable: true,
            observer: true, //修改swiper自己或子元素时，自动初始化swiper

        });
    }
    // 退出全屏时所做操作，因为这个视频全屏播放然后取消也会触发全屏的相关视频，所以要判断当触发源是video，则不进行退出全屏的操作。因为e.target返回的是标签信息无法进行判断，所以这里使用的e.path  （不太严谨）
    document.addEventListener("webkitfullscreenchange", function (e) {
        if (!e.currentTarget.webkitIsFullScreen && e.path.length < 6) {
            no_fullScreen()
        }
    });
    document.addEventListener("mozfullscreenchange", function (e) {
        if (!e.currentTarget.mozFullScreen && e.path.length < 6) {
            no_fullScreen();
        }
    });

    // 预览窗口关闭
    $(".previewPPTX .close img").unbind("click").click(function () {
        $(".previewPPTX").css("display", "none");
        $(".previewPPTX .swiper-container").empty(); //点击课程进入课时列表，先把课程展示删除
        $(".previewPPTX .swiper-container").append('<div class="swiper-wrapper"></div><div class="swiper-button-next"></div><div class="swiper-button-prev"></div>');
        var swiper = new Swiper('.swiper-container-x', {
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            on: {
                slideChangeTransitionEnd: function () {
                    $.each(videoArr, function (index, item) {
                        item.pause();
                    })
                },
            },
            // effect: 'cube',
            mousewheel: true, //滚轮轮播
            // /过渡到slide一开始就加载，设置为true
            keyboard: true, //开启键盘控制翻页
            clickable: true,
            observer: true, //修改swiper自己或子元素时，自动初始化swiper
        });

    })
    // 点击查看课件，进入全屏
    $("#lookCourse").unbind("click").click(function (e) {
        var el = document.documentElement; //<html></html>元素
        var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen; //全屏得方法sessionStorage
        rfs.call(el);
        $(".swiper-button-prev").css("display", "none");
        $(".swiper-button-next").css("display", "none");
        $(".screenFullNone").css("display", "none");
        $(".content").css("visibility", "hidden");
        let allSwiper = $(".swiper-wrapper .swiper-slide");
        $.each(allSwiper, function (index, item) {
            if ($(this).attr("is_screen") == 0) {
                $(this).css("display", "none");
            }
        })
        videoArr = $(".swiper-container video,.swiper-container audio");
        $(".centerBox").css({
            width: "100%",
        })
        $(".previewPPTX .PPTXCon").css("padding", "0");
    })
})